<template>
<view>
    <view class="search-box">
    <uni-search-bar
      radius="20"
      cancelButton="none"
      placeholder="搜索小说"
      @input="handleInput"
    ></uni-search-bar>
  </view>
  <view class="search-results">
    <view v-if="searchResults.length > 0">
      <view
        class="result-item"
        v-for="item in searchResults"
        :key="item.id"
        @click="goToBookDetail(item.id)"
      >
        <image class="book-cover" :src="item.cover" mode="aspectFill"></image>
        <text class="book-title">{{ item.title }}</text>
      </view>
    </view>
    <view v-else class="no-results">暂无搜索结果</view>
  </view>
</view>
</template>

<script>
export default {
  data() {
    return {
      timer: null,
      kw: "",
      searchResults: [],
    };
  },
  methods: {
    handleInput(e) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.kw = e.detail.value;
        this.searchBooks();
      }, 500);
    },
    async searchBooks() {
      if (!this.kw) {
        this.searchResults = [];
        return;
      }
      try {
        const res = await uni.request({
          url: "/api/books/search", // 替换为你的搜索接口地址
          method: "GET",
          data: { keyword: this.kw },
        });
        if (res[1].statusCode === 200) {
          this.searchResults = res[1].data;
        } else {
          uni.showToast({
            title: "搜索失败",
            icon: "none",
          });
        }
      } catch (err) {
        console.error(err);
        uni.showToast({
          title: "搜索出错",
          icon: "none",
        });
      }
    },
    goToBookDetail(bookId) {
      uni.navigateTo({
        url: `/pages/bookDetail/bookDetail?bookId=${bookId}`,
      });
    },
  },
};
</script>

<style scoped>
.search-box {
  padding: 20px;
}
.search-results {
  padding: 0 20px;
}
.result-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}
.book-cover {
  width: 60px;
  height: 80px;
  margin-right: 10px;
}
.book-title {
  flex: 1;
  font-size: 16px;
}
.no-results {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>